import React from "react";
import { NavBar ,Toast} from "antd-mobile";
// 导入axios
// import axios from "axios";
import {API} from '../../utils/api'
import "./index.scss";
// 导入utils获取当前定位城市的方法
import { getCurentCity } from "../../utils";
// 导入List组件
import { List, AutoSizer } from "react-virtualized";
import NavHeader from "../../components/NavHeader";
import style from './index.module.css'


// 数据格式化方法
const formatCityList = (list) => {
	const cityList = {};
	// 遍历list数组
	list.map((item) => {
		// 获取每一个城市的首字母
		const first = item.short.substr(0, 1);
		// 判断cityList中是否有这个分类
		if (cityList[first]) {
			// 如果有，直接想这个分类里面push数据
			cityList[first].push(item);
		} else {
			// 如果没有，就先创建一个数组，然后再把当前的城市信息添加到数组中
			cityList[first] = [item];
		}
	});
	// 获取索引数据
	const cityIndex = Object.keys(cityList).sort();
	return {
		cityList,
		cityIndex,
	};
};
// 封装处理字母索引的方法
const formatCityIndex = (letter) => {
	switch (letter) {
		case "#":
			return "当前定位";
		case "hot":
			return "热门城市";
		default:
			return letter.toUpperCase();
	}
};

// 索引高度
const TITLE_HEIGHT = 36;
// 城市名称高度
const NAME_HEIGHT = 50;

// 有房源的城市
const HOUSE_CITY=['北京','上海','广州','深圳']

class CityList extends React.Component {
	constructor(props){
		super(props)
		this.state = {
			cityList: {},
			cityIndex: [],
			activeIndex:0 //指定右侧索引列表高亮的索引号
		};

		// 创建ref对象
		this.cityListComponent = React.createRef()
	}
	

	async componentDidMount() {
		// 调用获取城市列表数据
		await this.getCityList();

		// 调用measureAllRows提前计算list中每一行的高度，实现scrollToRow的精确跳转
		this.cityListComponent.current.measureAllRows()
	}

	// 获取城市列表数据的方法
	async getCityList() {
		const res = await API.get("/area/city?level=1");
		const { cityList, cityIndex } = formatCityList(res.data.body);
		// 获取热门城市数据
		const hotRes = await API.get("/area/hot");
		cityList["hot"] = hotRes.data.body;
		cityIndex.unshift("hot");
		// console.log(cityList,cityIndex)

		// 获取当前定位城市信息
		const curCity = await getCurentCity();
		// console.log(curCity)
		cityList["#"] = [curCity];
		cityIndex.unshift("#");

		this.setState({
			cityList,
			cityIndex,
		});
	}

	// 切换城市
	changeCity=({label,value})=>{
		if(HOUSE_CITY.indexOf(label)>-1){
			// 有房源数据
			localStorage.setItem('ytzf_city',JSON.stringify({label,value}))
			this.props.history.goBack()
		}else{
			Toast.info('该城市暂无房源', 1,null,false);
		}
	}

	rowRenderer = ({
		key,
		index, //索引号
		isScrolling, //当前项是否正在滚动
		isVisble, //当前项在list中是可见的
		style, //!!一定要给每一行添加该样式
	}) => {
		const { cityIndex, cityList } = this.state;
		const letter = cityIndex[index];
		return (
			<div key={key} style={style} className="city">
				<div className="title">{formatCityIndex(letter)}</div>
				{cityList[letter].map((item) => (
					<div className="name" key={item.value}
					onClick={()=>this.changeCity(item)}
					>
						{item.label}
					</div>
				))}
			</div>
		);
	};

	getRowHeight = ({ index }) => {
		const { cityList, cityIndex } = this.state;
		return TITLE_HEIGHT + cityList[cityIndex[index]].length * NAME_HEIGHT;
	};

	//渲染右侧索引列表的方法
	renderCityIndex = () => {
		const {cityIndex,activeIndex} =this.state
		return cityIndex.map((item,index) => (
			<li className="city-index-item" key={item}
			onClick={()=>{
				this.cityListComponent.current.scrollToRow(index)
			}}
			>
				<span className={activeIndex===index ?'index-active':''}>{item==='hot' ?'热':item.toUpperCase()}</span>
			</li>
		));
	};
	onRowsRendered=({startIndex})=>{
		if(startIndex!==this.state.activeIndex){
			this.setState({
				activeIndex:startIndex
			})
		}
	}

	render() {
		return (
			<div className="citylist">
				<NavHeader>
					城市选择
				</NavHeader>

				{/* 城市列表 */}
				<AutoSizer>
					{({ width, height }) => (
						<List
							ref={this.cityListComponent}
							width={width}
							height={height}
							rowCount={this.state.cityIndex.length}
							rowHeight={this.getRowHeight}
							rowRenderer={this.rowRenderer}
							onRowsRendered={this.onRowsRendered}
							scrollToAlignment='start'
						/>
					)}
				</AutoSizer>

				{/* 右侧索引列表 */}
				<ul className="city-index">
					{this.renderCityIndex()}
				</ul>
			</div>
		);
	}
}
export default CityList;
